package ru.urfc.portal.ui.client.renderers;

import java.util.List;

import ru.urfc.portal.ui.client.descriptor.CompositeGridField;
import ru.urfc.portal.ui.client.descriptor.GridField;

import com.extjs.gxt.ui.client.data.ModelData;
import com.google.gwt.dom.client.Element;

public class AzimuthRenderer extends SimpleRenderer {
	
	public static final int DIVIDER = 100;
	
	CompositeGridField compositeGridField;
	
	public AzimuthRenderer(CompositeGridField compositeGridField, Element element) {
		super(compositeGridField, element);
		this.compositeGridField = compositeGridField;
	}

	@Override
	public String render(ModelData modelData) {
		List<GridField> gridFields = compositeGridField.getGridFields();		
		Double minDegrees = gridFields.get(0).<Double>getValue(modelData);
		Integer minMinutes = gridFields.get(1).<Integer>getValue(modelData);
		Double maxDegrees = gridFields.get(2).<Double>getValue(modelData);
		Integer maxMinutes = gridFields.get(3).<Integer>getValue(modelData);
		String min = eval(minDegrees, minMinutes);
		String max = eval(maxDegrees, maxMinutes);
		if (minDegrees == null && maxDegrees == null) {
			return "-";
		}
		return min + (minDegrees == null || maxDegrees == null? "": " - ") + max;
	}

	private String eval(Double degrees, Integer minutes) {
		if (degrees == null) {
			return "";
		}
		Double degreesX100 = degrees * DIVIDER;
		degreesX100 = degreesX100 > 0? degreesX100 + 0.5D: degreesX100 - 0.5D;
		Integer fraction = degreesX100.intValue() - degrees.intValue() * DIVIDER;
		fraction = fraction < 0? -fraction: fraction;
		String resultMinutes = fraction == 0 && minutes == null? "": 
			(fraction == 0? minutes: fraction) + "'";
		return degrees.intValue() + "\u00B0" + resultMinutes;
	}
	
}
